﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.PropertyTypes;
using Proggy.Web.Cms.Core.Configuration.ConfigObjects;
using Proggy.Web.Cms.ContentModel;
using System.ComponentModel.DataAnnotations;
using Proggy.Web.Cms.Context;
using Proggy.Web.Cms.Core.Controllers;
using System.Web.Mvc;
using Proggy.Data.Abstract;
using Proggy.Data.Entities;
using Proggy.Web.Cms.Repositories.Membership;
using Proggy.Web.Cms.Core.Controllers.PropertyType;
using Proggy.Web.Cms.Cache;
using Proggy.Web.Cms.Repositories.Published;

namespace Proggy.Web.Cms.Core.PropertyTypes
{
    [PropertyType("Related pages", "~/Areas/ProggyCore/Views/EditorPartials/ContentPickerEditor.cshtml", RequiredConfigObjectType = typeof(ContentPickerConfigObject))]
    public class ContentPicker : ConfigurablePropertyTypeBase, IValidatablePropertyType
    {
        public ContentPicker() { }
        public ContentPicker(INodeRepository nodeRepo) {
            //this._publishedRepo = publishedRepo;
            this._nodeRepo = nodeRepo;
        
        }

        //private IPublishedContentRepository _publishedRepo;
        private INodeRepository _nodeRepo;
        

        /// <summary>
        /// The page ids
        /// </summary>
        public int[] ContentIds { get; set; }

        /// <summary>
        /// Validation
        /// </summary>
        /// <param name="vContext"></param>
        /// <param name="attr"></param>
        /// <returns></returns>
        public Tuple<bool, string> GetIsValid(ValidationContext vContext, ContentModelPropertyTypeAttribute attr)
        {
            // get config object
            var configObject = base.GetConfigObjectInValidationContext<ContentPickerConfigObject>(vContext, attr);

            // get count
            var count = this.ContentIds == null ? 0 : this.ContentIds.Count();

            // check count
            if (
                (configObject.MaxPages != null && count > configObject.MaxPages)
                ||
                (configObject.MinPages != null && count < configObject.MinPages)
              )
            {

                return new Tuple<bool, string>(false, "Minimum related pages is " + configObject.MinPages + " and maximum is " + configObject.MaxPages);

            }

            // check allowed
            if (configObject.AllowedContentModelTypeAliases != null && configObject.AllowedContentModelTypeAliases.Count > 0)
            {
                // check
                if (this._nodeRepo == null) {
                    try {
                        this._nodeRepo = DependencyResolver.Current.GetService<INodeRepository>();
                    }
                    catch(Exception ex) {
                        throw new Exception("Cannot create instance of INodeRepository: " + ex.Message);
                    }
                }

                // get 
                var content =
                    (List<KeyValuePair<int, NodeBase>>)
                    new ContentPickerController(this._nodeRepo)
                        .ContentPickerItems(this.ContentIds)
                        .Model;

                // iterate
                foreach (var item in content)
                {

                    // check
                    if (!configObject.AllowedContentModelTypeAliases.Contains(item.Value.TypeAlias))
                    {
                        return new Tuple<bool, string>(false, "One of the added items (ID = " + item.Key + " is a type of item not allowed in this content picker. Please remove.");
                    }
                }

            }

            // check unpublished
            if (!configObject.AllowUnPublishedContent)
            {

                try
                {
                    foreach (var contentId in this.ContentIds)
                    {
                        // get url
                        var url = UrlCache.GetUrlFromNodeId(contentId);
                    }

                    // if all ok then no problem
                }
                catch
                {
                    return new Tuple<bool, string>(false, "You have selected unpublished content");
                }

            }

            // ok
            return new Tuple<bool, string>(true, "");
        }

        //public static List<IContentModel> GetContentFromContentPickerObjectInFrontEnd(ContentPicker contentPicker)
        //{
        //    // output
        //    var output = new List<IContentModel>();
        //    try
        //    {
        //        // check
        //        if (FrontEndRequestContext.Current != null)
        //        {
        //            // iterate
        //            foreach (var id in contentPicker.ContentIds)
        //            {

        //                // find
        //                var content = FrontEndRequestContext.Current.CurrentCachedContentRepository.PublishedContent.SingleOrDefault(x => x.Id == id);

        //                // check
        //                if (content != null)
        //                {

        //                    // add
        //                    output.Add(content);
        //                }


        //            }
        //        }
        //    }
        //    catch { }

        //    // error
        //    return output;
        //}

    }
}
